package cq.zhcqk.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dou361.dialogui.DialogUIUtils;
import com.dou361.dialogui.bean.BuildBean;
import com.dou361.dialogui.listener.DialogUIListener;
import com.jimi_wu.ptlrecyclerview.Divider.BaseItemDecoration;
import com.jimi_wu.ptlrecyclerview.HeaderAndFooter.OnItemClickListener;
import com.jimi_wu.ptlrecyclerview.HeaderAndFooter.OnItemLongClickListener;
import com.jimi_wu.ptlrecyclerview.PullToLoad.OnLoadListener;
import com.jimi_wu.ptlrecyclerview.PullToLoad.PullToLoadRecyclerView;
import com.jimi_wu.ptlrecyclerview.PullToRefresh.OnRefreshListener;
import com.jimi_wu.ptlrecyclerview.SimpleAdapter.SimpleAdapter;
import com.jimi_wu.ptlrecyclerview.SimpleAdapter.ViewHolder;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.apache.http.Header;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cq.zhcqk.R;
import cq.zhcqk.adapter.AxstDetailAdapter;
import cq.zhcqk.base.BaseActivity;
import cq.zhcqk.util.AsyncHttpClientUtils;
import cq.zhcqk.util.Common;
import cq.zhcqk.util.GsonUtil;
import cq.zhcqk.util.StringUtil;
import cq.zhcqk.util.x5.X5WebView;
import cq.zhcqk.widget.DG_ListView;

/**
 * Created by zhangle on 2018/3/7.
 */
public class AXST_OrderListActivity extends AppCompatActivity implements View.OnClickListener{
    private LinearLayout lay1,lay2;
    private LinearLayout cLay1,cLay2;
    private TextView txt1,txt2;
    private View line1,line2;
    private int currPi = 0;
    private PullToLoadRecyclerView rcv;
    private ArrayList<Map<String, Object>> list;
    private int isConsume = 0;
    private String userId = "";
    private TextView no_content;

    private Context context;
    protected BuildBean buildBean;
    private Dialog dialog;
    private AsyncHttpClient httpClient;
    private Activity mActivity;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_axst_order);
        httpClient = AsyncHttpClientUtils.getInstance().getAsyncHttpClient();
        mActivity = AXST_OrderListActivity.this;
        context = this;

        lay1 = (LinearLayout) findViewById(R.id.lay1);
        lay2 = (LinearLayout) findViewById(R.id.lay2);
        txt1 = (TextView) findViewById(R.id.txt1);
        txt2 = (TextView) findViewById(R.id.txt2);
        no_content = (TextView) findViewById(R.id.no_content);
        line1 =  findViewById(R.id.line1);
        line2 =  findViewById(R.id.line2);
        lay1.setOnClickListener(this);
        lay2.setOnClickListener(this);
        initRecyclerView();
        initData();
    }

    protected void initData() {
        buildBean = DialogUIUtils.showLoading(this, "加载中...", true, true, false, false);
        initBack();
        getList(isConsume);
    }

    private void initBack(){
        ImageView back = (ImageView) findViewById(R.id.header_back);
        TextView title = (TextView) findViewById(R.id.header_text);
        title.setText("食堂点餐记录");
        back.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.header_back:
                finish();
                break;
            case R.id.lay1:
                setSelectBg(0);
                break;
            case R.id.lay2:
                setSelectBg(1);
                break;
        }
    }

    private void setSelectBg(int pi){
        if(currPi == pi){
            return;
        }
        currPi = pi;
        if(pi == 0){
            txt1.setTextColor(ContextCompat.getColor(context,R.color.read));
            line1.setBackgroundColor(ContextCompat.getColor(context,R.color.read));
            txt2.setTextColor(ContextCompat.getColor(context,R.color.black));
            line2.setBackgroundColor(ContextCompat.getColor(context,R.color.gray));
            isConsume = 0;
            getList(isConsume);
        }else if(pi == 1){
            txt1.setTextColor(ContextCompat.getColor(context,R.color.black));
            line1.setBackgroundColor(ContextCompat.getColor(context,R.color.gray));
            txt2.setTextColor(ContextCompat.getColor(context,R.color.read));
            line2.setBackgroundColor(ContextCompat.getColor(context,R.color.read));
            isConsume = 1;
            getList(isConsume);
        }
    }

    private void initRecyclerView(){
        rcv = (PullToLoadRecyclerView)findViewById(R.id.list1);

        rcv.setLayoutManager(new GridLayoutManager(context,1));
        rcv.setLoadEnable(false);
//        设置适配器，封装后的适配器只需要实现一个函数
        list = new ArrayList<>();
        rcv.setAdapter(new SimpleAdapter<Map<String, Object>>(context, list, R.layout.item_axst_order) {
            @Override
            protected void onBindViewHolder(ViewHolder holder, final Map<String, Object> data) {
                holder.<TextView>getView(R.id.time).setText(""+data.get("createDate"));
                holder.<TextView>getView(R.id.num).setText(""+((List<Map<String, Object>>) data.get("dicDishes")).size());
                holder.<TextView>getView(R.id.total).setText("¥"+data.get("money"));
                String st = data.get("consumeType")+"";
                if("0".equals(st)){
                    holder.<TextView>getView(R.id.state).setVisibility(View.GONE);
                    holder.<Button>getView(R.id.confirm).setVisibility(View.VISIBLE);
                    holder.<TextView>getView(R.id.state).setText("未消费");
                    holder.<TextView>getView(R.id.state).setTextColor(getResources().getColor(R.color.read));
                    holder.<Button>getView(R.id.confirm).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            confirmAl(data.get("orderId")+"");
                        }
                    });
                }else if("1".equals(st)){
                    holder.<TextView>getView(R.id.state).setVisibility(View.VISIBLE);
                    holder.<Button>getView(R.id.confirm).setVisibility(View.GONE);
                    holder.<TextView>getView(R.id.state).setText("已消费");
                    holder.<TextView>getView(R.id.state).setTextColor(getResources().getColor(R.color.green));
                }

                AxstDetailAdapter axstDetailAdapter = new AxstDetailAdapter(context, (List<Map<String, Object>>) data.get("dicDishes"));
                holder.<DG_ListView>getView(R.id.detail_List).setAdapter(axstDetailAdapter);
            }
        });
//        设置刷新监听
        rcv.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onStartRefreshing() {
                getList(isConsume);
            }
        });
//        设置加载监听
        rcv.setOnLoadListener(new OnLoadListener() {
            @Override
            public void onStartLoading(int skip) {
            }
        });
//        设置分割线
        rcv.addItemDecoration(new BaseItemDecoration(context,R.color.gray_bg));

        rcv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void OnItemClick(int position) {
//                Intent intent = new Intent(context, ListDetailSampleActivity.class);
//                intent.putExtra("cid",(int) Double.parseDouble(String.valueOf(list.get(position).get("cid")))+"");
//                startActivity(intent);
//                getActivity().overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
            }
        });
        rcv.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(int position) {
                return true;
            }
        });
    }

    private void confirmAl(final String orderId){
        DialogUIUtils.showAlert(mActivity, "温馨提示", "请确认消费此订单", "", "", "确定", "取消", false, true, true, new DialogUIListener() {
            @Override
            public void onPositive() {
                confirm(orderId);
            }

            @Override
            public void onNegative() {

            }

        }).show();
    }

    private void confirm(String oid){
        RequestParams params = new RequestParams();
        params.add("oid",oid+"");
        String url = "";
        url = Common.URL+Common.DOCONSUME;
        buildBean.show();
        httpClient.post(url,params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                System.out.println("onSuccess："+response);
                Map<String, Object> map = GsonUtil.GsonToMaps(response+"");
                if(StringUtil.stringToInt(map.get("code")+"") != 0){
                    Toast.makeText(context,"确认失败，请稍后再试",Toast.LENGTH_SHORT).show();
                    return;
                }
                Toast.makeText(context,"消费成功",Toast.LENGTH_SHORT).show();
                getList(isConsume);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable,
                        errorResponse);
                System.out.println("errorResponse："+errorResponse);
                Toast.makeText(context,"确认失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                System.out.println("responseString："+responseString);
                Toast.makeText(context,"确认失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                DialogUIUtils.dismiss(buildBean);
            }
        });
    }

    private void getList(int isConsume1){
        RequestParams params = new RequestParams();
        params.add("isConsume",isConsume1+"");
        String url = "";
        url = Common.URL+Common.PAYEDDISHES;
        buildBean.show();
        httpClient.post(url,params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                System.out.println("onSuccess："+response);
                Map<String, Object> map = GsonUtil.GsonToMaps(response+"");
                if(StringUtil.stringToInt(map.get("code")+"") != 0){
                    Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
                    return;
                }
                ArrayList<Map<String, Object>> listNew = null;
                listNew = (ArrayList<Map<String, Object>>) map.get("data");
                list.clear();
                list.addAll(listNew);
                if (list.size()>0){
                    no_content.setVisibility(View.GONE);
                }else {
                    no_content.setVisibility(View.VISIBLE);
                }
                rcv.completeRefresh();
                rcv.completeLoad(1);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable,
                        errorResponse);
                System.out.println("errorResponse："+errorResponse);
                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                System.out.println("responseString："+responseString);
                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                DialogUIUtils.dismiss(buildBean);
            }
        });
    }
}
